import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import find from 'lodash/find';
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem } from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import DetailInfo from './Info';
import Detail from './Detail';
import AddOrEditDevice from './AddOrEditDevice';
import Vendor from './Vendor';
import Check from '../Card/ApplicationCommon/check';
import ReactEcharts from 'echarts-for-react';
import WaterType from '../Meters/WaterType';
import './index.less'

const FormItem = Form.Item;
const { confirm } = Modal;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ vendor_meter, loading,global }) => ({
  vendor_meter,
  global,
  loading: loading.models.vendor_meter,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      maxWidth:200,
    };

  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      vendor_meter: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.ant-table-body');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        vendor_meter: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'vendor_meter/changeTableY',
      });
      dispatch({
        type: 'vendor_meter/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'vendor_meter/changeLoaded',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
    this.setState({
      maxWidth: document.querySelector('.table-page').offsetWidth-20
    },function () {
      console.log('maxWidth',this.state.maxWidth)
    })
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'vendor_meter/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;

    dispatch({
      type: 'vendor_meter/changeTableY',
    });
  };


  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'vendor_meter/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      vendor_meter: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label={'开始日期'}>
          {getFieldDecorator('start_date', {
            initialValue: moment(searchParams.start_date),
          })(
            <DatePicker
              style={{width: '120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />
          )}
        </FormItem>
        <FormItem label={'结束日期'}>
          {getFieldDecorator('end_date', {
            initialValue: moment(searchParams.end_date),
          })(
            <DatePicker
              style={{width: '120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />
          )}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                  start_date: moment(fieldsValue.start_date).format('YYYY-MM-DD'),
                  end_date: moment(fieldsValue.end_date).format('YYYY-MM-DD'),
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        </FormItem>

      </Form>
    );
  }

  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'vendor_meter/add',
      payload: {
        ...formValues,
      },
      callback() {
        message.success('新建设备成功');
        that.setState({
          addModal: false,
        });
        const {
          vendor_meter: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      start_date:moment(new Date().getFullYear()+'-'+(parseInt(new  Date().getMonth())+1)+'-'+'01' , "YYYY-MM-DD").format("YYYY-MM-DD"),
      end_date:new Date().getDate()===1?moment(new Date().getFullYear()+'-'+(parseInt(new  Date().getMonth())+1)+'-'+'01').format('YYYY-MM-DD'):moment().subtract(1, "day").format("YYYY-MM-DD"),
      page: 1,
      per_page: 30,
    });
  };

  getOption = () => {
    let lastMonth = [];
    let legend=[];
    let  series=[]
    const {
      vendor_meter: { data },
    } = this.props;
    if(data[0]&&data[0].items) {
      for (let i = 0; i < data[0].items.length; i++) {
        let name = data[0].items[i].vendor_name;
        legend.push(name);
        let seriesitem={
          name:name,
          type:'line',
          smooth:true,
          lineStyle: {
            normal: {
              width: 4,
            }
          },
          data:[]
        }
        for (let j = 0; j < data.length; j++) {
          let date = data[j].date;
          if(i===0){
            lastMonth.push(date)
          }
          const findByName=find(data[j].items,(o)=>o.vendor_name===name)
          seriesitem.data.push(findByName?parseFloat(findByName.normal_rate):'')
        }
        series.push(seriesitem)

      }

    }else{
      return  {}
    }
    console.log('legend',legend)
    let option = {
      background: 'rgb(0,0,0)',
      title: {
        text: '抄读率'
      },
      color:['#da0422','#00da4a','#008cff','#f0b100'],
      tooltip: {
        trigger: 'axis',
      },
      legend: {
        data: legend
      },
      grid: {
        left: '2%',
        right: '2%',
        top:'15%',
        bottom: '4%',
        containLabel: true
      },
      dataZoom: [
        {
          type: 'slider',
          show: false,
          xAxisIndex: [0],
        },
        {
          type: 'inside',
          xAxisIndex: [0],
        },
      ],
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: lastMonth,

      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 100,
        interval: 20,
        axisLabel: {
          formatter: '{value} %',
        },
      },
      series:series
    };
    return option;
  };

  render() {
    const that = this;
    const {
      vendor_meter: { data, loading, tableY, meta, summary, selectedRowKeys, additional },
      global:{gridTableW}
    } = this.props;
    const columns = [
      {
        title: '采集时间',
        dataIndex: 'date',
        width: 100,
      },
    ];
    let tableX=100
    if(data[0]&&data[0].items){
      for(let i=0;i<data[0].items.length;i++){
        let name=data[0].items[i].vendor_name
        columns.push( {
          title: name,
          className:`vendor-meter${i%4+1}`,
          children: [
            {
              title: '水表总量',
              dataIndex:`total_count${i+1}`,
              width: 70,
              className:`vendor-meter${i%4+1}`,
              render:(text,record)=>{
                const findByName=find(record.items,(o)=>o.vendor_name===name)
                return findByName?findByName.total_count:''
              }
            },
            {
              title: '正常抄读数',
              dataIndex:`normal_count${i+1}`,
              className:`vendor-meter${i%4+1}`,
              width: 90,
              render:(text,record)=>{
                const findByName=find(record.items,(o)=>o.vendor_name===name)
                return findByName?findByName.normal_count:''
              }
            },
            {
              title: '异常数量',
              dataIndex:`abnormality_count${i+1}`,
              className:`vendor-meter${i%4+1}`,
              width: 70,
              render:(text,record)=>{
                const findByName=find(record.items,(o)=>o.vendor_name===name)
                return findByName?findByName.abnormal_count:''
              }
            },
            {
              title: '抄读率',
              dataIndex: `normal_rate${i+1}`,
              className:`vendor-meter${i%4+1}`,
              width: 60,
              render:(text,record)=>{
                const findByName=find(record.items,(o)=>o.vendor_name===name)
                return findByName?findByName.normal_rate:''
              }
            },
          ]
        },)
      }
      tableX=100+(data[0].items.length*290)
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>厂商水表分析</span>
      </div>
      <div className="table-page">
        <div className="table-info">
          {
            summary.map((item,index)=>{
              return       <div key={index} className="table-info-item">
                <p>{item.vendor_name} 平均抄读率</p>
                <h4>{item.normal_rate}</h4>
              </div>
            })
          }

        <div size="large" className="table-info-right-item">
          <Button
            icon="appstore"
            style={{ marginLeft: 8 }}
            type="primary"
            className={'btn-cyan'}
            onClick={
              () => {
                this.setState({
                  typeModal: true,
                });
              }
            }
          >
            水表厂商管理
          </Button>
            <Button
              icon="export"
              style={{ marginLeft: 8 }}
              type="primary"
              onClick={
                () => {
                  message.info('功能开发中');
                  return false
                  this.setState({
                    addModal: true,
                  });
                }
              }
            >
              导出厂商水表数据
            </Button>
          </div>
        </div>
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div>
          <Table
            style={{color: '#fff',maxWidth:this.state.maxWidth+'px'}}
            className="custom-small-table meter-table vendor-meter"
            loading={loading}
            rowKey={'date'}
            dataSource={[...data].reverse()}
            columns={columns}
            pagination={false}
            size="small"
            scroll={{x: tableX, y: tableY}}
          />
        </div>


      </div>
      <div className="bottom-analysis"><ReactEcharts
        option={this.getOption()}
        style={{ height: '100%', width: '100%' }}
        theme='my_theme'
        //onChartReady={this.onChartReadyCallback}
        //onEvents={EventsDict}
      />
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={`修改 : ${this.state.editRecord.name}`}/>}
        destroyOnClose
        visible={this.state.editModal}
        centered
        onOk={this.handleEdit}
        className="editModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ editModal: false, editRecord: {} });
        }}

      >
        <AddOrEditDevice
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EditForm = inst}
        />

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.addModal} modalClass="addModal" title="新建设备"/>}
        visible={this.state.addModal}
        centered
        onOk={this.handleAdd}
        className="addModal"
        onCancel={() => {
          this.setState({ addModal: false });
        }}

      >
        <AddOrEditDevice
          wrappedComponentRef={(inst) => this.AddForm = inst}
        />

      </Modal>
      <Drawer
        title={`水表厂商管理`}
        placement="right"
        onClose={() => {
          this.setState({
            typeModal: false,
            editRecord: {},
          });
        }}
        width={700}
        visible={this.state.typeModal}
      >
        <Vendor></Vendor>
      </Drawer>
    </div>;
  }
}

export default BasicList;
